<!-- 工序委外 -->

<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
  </pageHeader>
  <div class="search-box">
    <div>
      <a-space>
        <a-input-group>
          <a-select
            :style="{ width: '120px' }"
            placeholder="请选择"
            v-model="currSelectVal"
            :default-value="currSelectVal"
          >
            <a-option value="number">委外单号 </a-option>
          </a-select>
          <a-input-search
            :style="{ width: 'auto' }"
            placeholder="请输入"
            v-model="currSelectSearch"
            search-button
            @search="search"
          />
        </a-input-group>
        <a-select
          placeholder="请选择"
          v-model="selectState"
          @change="searchState"
        >
          <template #prefix>状态：</template>
          <a-option :value="1">待确认</a-option>
          <a-option :value="2">已确认</a-option>
          <a-option :value="3">已出库</a-option>
          <a-option :value="4">入库中</a-option>
          <a-option :value="5">已入库</a-option>
          <a-option :value="6">收货中</a-option>
          <a-option :value="7">已收货</a-option>
          <a-option :value="8">已发货</a-option>
          <a-option :value="0">全部</a-option>
        </a-select>
        <a-button type="outline" @click="reset">
          <template #icon>
            <icon-refresh />
          </template>
          <template #default>重置</template>
        </a-button>
      </a-space>
    </div>
    <div>
      <a-space>
        <a-button status="success">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>
        <a-button status="warning">
          <template #icon>
            <icon-export rotate="-90" />
          </template>
          <template #default>导出</template>
        </a-button>
      </a-space>
    </div>
  </div>
  <div style="padding: 10px">
    <tableTurn :tableData="getData" :args="args" ref="tableRef">
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        v-for="item in selectedHeader"
        :key="item.code"
        :title="item.name"
        :data-index="item.code"
        :width="150"
        align="center"
      >
        <template v-if="item.code === 'pickDate'" #cell="{ record }">
          {{ dayjs(record.pickDate).format('YYYY-MM-DD ') }}
        </template>

        <template v-else-if="item.code === 'planDate'" #cell="{ record }">
          {{ dayjs(record.planDate).format('YYYY-MM-DD') }}
        </template>

        <template v-else-if="item.code === 'CreatedAt'" #cell="{ record }">
          {{ dayjs(record.CreatedAt).format('YYYY-MM-DD hh:mm:ss') }}
        </template>

        <template v-else-if="item.code === 'priority'" #cell="{ record }">
          <a-typography-text
            v-if="record.priority === 1"
            style="color: #999999"
          >
            低
          </a-typography-text>
          <a-typography-text v-if="record.priority === 2" type="primary">
            中
          </a-typography-text>
          <a-typography-text v-if="record.priority === 3" type="warning">
            高
          </a-typography-text>
          <a-typography-text v-if="record.priority === 4" type="danger">
            紧急
          </a-typography-text>
        </template>

        <template v-else-if="item.code === 'okState'" #cell="{ record }">
          <a-typography-text v-if="record.state === 1" style="color: #999999">
            预收获
          </a-typography-text>
          <a-typography-text v-else type="success"> 已收货 </a-typography-text>
        </template>

        <template v-else-if="item.code === 'TaskNumber'" #cell="{ record }">
          {{ record.TaskNumber || '--' }}
        </template>
      </a-table-column>

      <a-table-column :width="150" align="center">
        <template #title> 确认状态 </template>
        <template #cell="{ record }">
          <div
            class="status"
            :style="{
              color: orderStatus.filter((ele) => ele.id === record.state)[0]
                ?.backgroundColor,
            }"
          >
            <p
              :style="{
                'background': orderStatus.filter(
                  (ele) => ele.id === record.state
                )[0]?.backgroundColor,
                'box-shadow': `0px 0px 5px`,
              }"
            ></p>
            {{ orderStatus.filter((ele) => ele.id === record.state)[0]?.value }}
          </div>
        </template>
      </a-table-column>
      <a-table-column :width="150" align="center">
        <template #title> 查看二维码 </template>
        <template #cell="{ record }">
          <qrcode-vue :value="`${record.id}`" :size="50" level="H"></qrcode-vue>
        </template>
      </a-table-column>
      <a-table-column :width="150" fixed="right" title="操作" align="center">
        <template #title> 操作 </template>
        <template #cell="{ record }">
          <!-- <a-button
            type="text"
            v-if="record.state === 1"
            @click="confirm(record.id)"
            >确认</a-button
          >
          <a-button
            type="text"
            v-if="record.state === 1"
            @click="EditOutsourcing(record.id)"
            >编辑</a-button
          >
          <a-button type="text" @click="DetailsOutsourcing(record.id)"
            >详情</a-button
          >

          <a-popconfirm
            v-if="record.state === 1"
            content="确认删除?"
            type="error"
            @ok="del(record.id)"
          >
            <a-button type="text" status="danger">删除</a-button>
          </a-popconfirm> -->

          <a-tooltip v-if="record.state === 1" content="确认">
            <IconFont
              type="icon-zhengque"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="confirm(record.id)"
            />
          </a-tooltip>
          <a-tooltip v-if="record.state === 1" content="编辑">
            <IconFont
              type="icon-edit"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="EditOutsourcing(record.id)"
            />
          </a-tooltip>
          <a-tooltip content="详情">
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="DetailsOutsourcing(record.id)"
            />
          </a-tooltip>

          <a-tooltip v-if="record.state === 1" content="删除">
            <a-popconfirm
              content="确认删除？"
              type="error"
              @ok="del(record.id)"
            >
              <IconFont
                type="icon-delete"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
              />
            </a-popconfirm>
          </a-tooltip>
        </template>
      </a-table-column>
    </tableTurn>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import {
    getOutsourcingAll,
    delOutsourcingOne,
    confirmOutsourcingOne,
  } from '@/api/produce-management/production-operation/index';
  import QrcodeVue from 'qrcode.vue';

  const selectState: number | null = ref(null);
  const router = useRouter();
  const title: string = '工序委外';
  const breadCrumb: string[] = ['生产管理', '生产作业', '工序委外'];
  const modelVisible = ref(false);
  const formHeaderSettingVisible = ref(false);
  let tableRef: any = ref(); // 储存table的ref
  let currSelectVal = ref(); // 储存当前下拉选择框的值
  let currSelectSearch = ref(''); // 储存下拉选择框对应的搜索框的值
  const beginTime = ref();
  const endTime = ref();
  const ownList = ref();
  const saveUserId = ref<any>(
    JSON.parse(sessionStorage.getItem('loginInfo') as any)
  );
  const ShipmentId = ref();
  const outsourcingTime = ref();
  // 表格配置
  const args = reactive({
    stripe: true,
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮以客户名称来作为key
  });

  const orderStatus = [
    { id: 1, value: '待确认', backgroundColor: '#cccccc' },
    { id: 2, value: '已确认', backgroundColor: '#009933' },
    { id: 3, value: '已出库', backgroundColor: '#009933' },
    { id: 4, value: '入库中', backgroundColor: '#1fa4b3' },
    { id: 5, value: '已入库', backgroundColor: '#1fa4b3' },
    { id: 6, value: '收货中', backgroundColor: '#1fa4b3' },
    { id: 7, value: '已收货', backgroundColor: '#1fa4b3' },
    { id: 8, value: '已发货', backgroundColor: '#1fa4b3' },
  ];

  // 储存表头数据
  const priorityData = ref(); // 储存搜索优先级的值
  const headerSetting = reactive<any>({
    list: [],
  });

  const getData = async (page: any) => {
    try {
      const msg: any = {};
      if (currSelectVal.value !== '' && currSelectSearch.value !== '')
        msg[currSelectVal.value] = currSelectSearch.value;
      if (selectState.value) msg.state = selectState.value;
      if (priorityData.value) msg.priority = priorityData.value;
      if (ownList.value) msg.ownList = ownList.value;
      if (beginTime.value)
        msg.outsourcingMaxDate = new Date(beginTime.value).toJSON();
      if (endTime.value)
        msg.outsourcingMinDate = new Date(endTime.value).toJSON();
      let res = await getOutsourcingAll({
        ...page,
        ...msg,
        outsourcingType: 2,
      });

      if (res.content === null || res.content === undefined) {
        res.content = [];
      }

      res.content.map((item: any) => {
        item.show = false;
        return item;
      });

      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const searchState = (val: number) => {
    tableRef.value.loadData();
  };
  const columns = [
    {
      code: 'number',
      isDefault: 1,
      name: '委外单号',
    },
    {
      code: 'managementNumber',
      isDefault: 1,
      name: '产品编码',
    },
    {
      code: 'managementName',
      isDefault: 1,
      name: '产品名称',
    },

    {
      code: 'spec',
      isDefault: 1,
      name: '规格型号',
    },
    {
      code: 'amount',
      isDefault: 1,
      name: '需求数量',
    },
    {
      code: 'TaskNumber',
      isDefault: 1,
      name: '关联生产任务单',
    },
  ];

  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  const reset = () => {
    currSelectVal.value = '';
    currSelectSearch.value = '';
    priorityData.value = undefined;
    beginTime.value = undefined;
    endTime.value = undefined;
    outsourcingTime.value = [];
    selectState.value = undefined;
    tableRef.value.loadData();
  };

  const search = () => {
    tableRef.value.loadData();
  };

  const onChange = (value: any) => {
    if (value !== undefined) {
      beginTime.value = value[0];
      endTime.value = value[1];
      tableRef.value.loadData();
    } else {
      tableRef.value.loadData();
    }
  };

  const addOutbound = (e?: number) => {
    router.push({
      name: 'AddSalesOutbound',
    });
  };

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: any = [];
    columns.forEach((item: any) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  const setShipment = (id: number) => {
    modelVisible.value = true;
    ShipmentId.value = id;
  };

  const goDeliveryDetails = async (id: number) => {
    router.push({
      name: 'productionPickDetails',
      query: { id },
    });
  };

  const EditOutsourcing = (id: number) => {
    router.push({
      name: 'outsourcingDetails',
      query: { id, type: 'edit', name: '编辑工序委外' },
    });
  };

  const DetailsOutsourcing = (id: number) => {
    router.push({
      name: 'outsourcingDetails',
      query: { id, type: 'details', name: '工序委外详情' },
    });
  };

  const del = (id: number) => {
    try {
      delOutsourcingOne({ id });
      tableRef.value.loadData();
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const confirm = async (id: number) => {
    try {
      await confirmOutsourcingOne({ id });
      tableRef.value.loadData();
    } catch (err: unknown) {
      console.log(err);
    }
  };
</script>

<style scoped lang="less">
  .search-box {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 0 10px;
    margin-top: -7px;
  }
  :deep(.arco-space-item) {
    margin-top: 10px;
  }
  .Detail-item {
    cursor: pointer;
  }

  :deep(.arco-tabs-content) {
    padding-top: 0px;
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: center;

    p {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 10px;
    }
  }
</style>
